import os
import sys
import subprocess

def run_command(command, cwd=None):
    """
    运行 shell 命令并打印输出
    """
    result = subprocess.run(command, shell=True, cwd=cwd,text=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE,encoding='utf-8')
    if result.returncode != 0:
        print(f"{command}: error")
        print(f"result.stderr:{result.stderr}")
        sys.exit(-1)
    return result


def create_local_branch_for_submodules(branch_name, repo_path):

    submodules = run_command("git submodule", cwd=repo_path).stdout
    
    for line in submodules.splitlines():
        submodule_path = line.split()[1]
        submodule_repo_path = os.path.join(repo_path, submodule_path)
        if os.path.exists(submodule_repo_path):
            print(f"updata submodules:{submodules}")
            force_merge_remote_branch(submodule_repo_path, branch_name)
        else:
            print(f"没有权限访问子模块仓库: {submodule_path}")


def force_merge_remote_branch(local_repo_path, remote_branch):
    """
    将远端分支拉取并强制合并到本地当前分支，并强制检出当前分支
    :param local_repo_path: 仓库的本地路径
    :param remote_branch: 远端分支名称
    """
    # 确保在正确的本地仓库路径下运行
    os.chdir(local_repo_path)
    
    # 强制检出当前分支
    print("Force checking out current branch...")
    run_command("git checkout --force", cwd=local_repo_path)
    # 获取远端更新
    print("Fetching updates from remote...")
    run_command("git fetch origin", cwd=local_repo_path)

    # 强制合并远端分支到本地当前分支
    print(f"Force merging remote branch {remote_branch} into current local branch...")
    run_command(f"git merge -Xtheirs origin/{remote_branch}", cwd=local_repo_path)

    create_local_branch_for_submodules(remote_branch,local_repo_path)
    
    print("Merge and checkout completed.")

# 示例用法
if __name__ == "__main__":
   # 检查命令行参数数量
    if len(sys.argv) < 3:
        print("Usage: python script.py <local_repo_path> <remote_branch>")
        sys.exit(1)
    current_directory = os.getcwd()
    local_repo_path = os.path.join(current_directory, sys.argv[1])
    remote_branch = sys.argv[2]
    

    # 输出当前工作目录
    print(f"Current working directory: {local_repo_path}")
    # 调用函数进行远程分支合并和检出
    force_merge_remote_branch(local_repo_path, remote_branch)

    
